package com.vains.filter;

import com.vains.constant.ApplicationNameConstants;
import com.vains.constant.GlobalConstants;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;


/**
 * 全局过滤器，使用配置类形式，直接构造bean，使用注解完成Ordered接口功能,统计接口调用时间
 * @author vains
 */
@Configuration
public class GlobalGatewayFilterConfig {

    @Bean
    @Order(-100)
    public GlobalFilter elapsedGlobalFilter() {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            URI uri = request.getURI();
            if (uri.getRawPath().equals(GlobalConstants.AUTHORIZATION_CODE_URI) || uri.getRawPath().equals(GlobalConstants.LOGIN_PROCESS_URL)) {
                // String url = uri.getScheme() + "://" + uri.getHost() + "/" + ApplicationNameConstants.AUTH_SERVER_NAME;
                URIBuilder uriBuilder = new URIBuilder();
                uriBuilder.setScheme(uri.getScheme());
                uriBuilder.setHost(uri.getHost());
                uriBuilder.setPort(uri.getPort());
                uriBuilder.setPath(ApplicationNameConstants.AUTH_SERVER_NAME);

                String url = uriBuilder.toString();

                ServerHttpRequest newRequest = request.mutate().headers(httpHeaders -> httpHeaders.add(GlobalConstants.BEFORE_REDIRECT_URI_KEY, url)).build();
                ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
                return chain.filter(newExchange);
            }
            return chain.filter(exchange);
        };
    }

    /**
     * 失败返回message提示用户
     * @param exchange HTTP请求-响应交互
     * @param url 重定向地址
     * @return  Mono<Void>
     */
    private Mono<Void> fallBack(String url, ServerWebExchange exchange){
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location", url);
        return exchange.getResponse().setComplete();
    }
}
